<template>
  <div class="order-confirm-page">
    <div class="order-confirm-header">
      <back-title :message="message"></back-title>
    </div>
    <div class="order-confirm-body">
      <div class="address-default">
        <van-contact-card type="add" @click="goEdit" v-if="thisAdress.length === 0" />
        <van-cell is-link @click="goEdit" :label="getLabel" v-else>
          <template #title>
            <span class="custom-title">{{getTitle}}</span>
            <van-tag plain type="danger" v-if="thisAdress[0].default_flag === '0'">默认</van-tag>
          </template>
        </van-cell>
      </div>
      <div class="goods-info item-block">
        <div v-for="(item, index) in thisgoodsInfo" :key="index">
          <van-card :num="item.count" :price="item.selling_price" :desc="item.goods_intro" :title="item.goods_name"
            thumb="https://img01.yzcdn.cn/vant/ipad.jpeg">
            <template #tags>
              <van-tag plain type="danger">标签</van-tag>
              <van-tag plain type="danger">标签</van-tag>
            </template>
            <template #footer>
              <van-stepper v-model="item.num" input-width="25px" button-size="20px" />
            </template>
          </van-card>
        </div>
      </div>
      <div class="total-floor item-block">
        <div class="total-info">
          <van-cell title="商品总额" :value="totalPrice" />
          <van-cell title="运费" :value="freigh" is-link />
        </div>
      </div>
      <div class="other-info-floor item-block">
        <van-cell title="发票" value="电子发票(商品明细个人)" is-link />
        <van-cell title="支付方式" is-link :value="value" @click="showPopup()" />
        <van-popup v-model="showPicker" round position="bottom" :style="{ height: '30%' }">
          <van-picker title="支付方式" show-toolbar :columns="columns" @confirm="onConfirm" @cancel="onCancel" />
        </van-popup>
      </div>
    </div>
    <div class="order-confirm-footer">
      <div class="footer-floor item-block">
        <van-button round type="info" size="large" @click="ToPay()">提交订单</van-button>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import axios from 'axios'
  // import eventBus from '../../views/Me/base/eventBus.js'
  import BackTitle from '../BackHeader/BackTitle.vue'
  export default {
    components: {
      BackTitle
    },
    data() {
      return {
        goodsItems: [],
        // goodsID: 0,
        radio: '',
        // num: 1,
        freigh: '免运费',
        // index: 0,
        info: 0,
        value: '在线支付',
        skuData: [],
        columns: ['在线支付', '货到付款'],
        showPicker: false,
        message: '订单确认',
        currentContact: {
          name: '张三',
          tel: '13000000000'
        }
      }
    },
    methods: {
      ...mapMutations(['SET_ORDER_NUM']),
      phoneNumFilter(value) {
        if (!value) {
          return ''
        }
        let str = value
        str = str.toString().replace(/^(\d{3})(\d{4})(\d{4})/g, '$1****$3')
        return str
      },
      getInfo(val) {
        return this.goodsInfo.filter(value => {
          return value.goods_id === Number(val)
        })
      },
      // 去支付
      ToPay() {
        if (this.thisAdress.length === 0) {
          this.$toast('请选择地址！')
        } else {
          const params = {
            order_nu: this.orderNum,
            user_id: this.loginToken.userId,
            total_price: this.totalPrice,
            pay_status: "未支付",
            pay_type: this.value,
            order_status: "未完成",
            is_deleted: 0
          }
          const params1 = {
            order_nu: this.orderNum,
            user_name: this.thisAdress[0].consignee,
            user_phone: this.thisAdress[0].consignee_phone,
            province_name: this.thisAdress[0].province_name,
            city_name: this.thisAdress[0].city_name,
            region_name: this.thisAdress[0].region_name,
            detail_address: this.thisAdress[0].detail_address
          }
          axios.post(axios.defaults.baseURI + "books/mallorder/", params).then(res => {
            console.log(res)
            if (res.code === 201) {
              axios.post(axios.defaults.baseURI + "books/orderaddress/", params1).then(res => {
                console.log(res)
              })
              for (var i in this.thisgoodsInfo) {
                const params2 = {
                  order_nu: this.orderNum,
                  goods_id: this.thisgoodsInfo[i].goods_id,
                  goods_name: this.thisgoodsInfo[i].goods_name,
                  goods_cover_img: this.thisgoodsInfo[i].goods_cover_img,
                  selling_price: this.thisgoodsInfo[i].selling_price,
                  goods_count: this.thisgoodsInfo[i].count
                }
                axios.post(axios.defaults.baseURI + "books/orderitem/", params2).then(res => {
                  console.log(res)
                })
              }
            } else {
              this.$toast('请求失败')
            }
          })
          this.$router.push({
            path: '/Payment',
            query: {
              price: this.totalPrice
            }
          })
        }
      },
      onAdd() {
        this.$router.push({
          name: 'AddAddress'
        })
      },
      onEdit() {},
      showPopup() {
        this.showPicker = true
      },
      goEdit() {
        this.$router.push({
          path: '/Set/UserAddress',
          query: {
            flag: 1
          }
        })
      },
      onConfirm(value) {
        this.value = value
        this.showPicker = false
      },
      onCancel() {
        this.showPicker = false
      }
    },
    // created:在模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图。
    // mounted:在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作。
    created() {
      this.goodsItems = this.goodsItem
      var today = new Date()
      var year = today.getFullYear() + ""
      var month = today.getMonth() + 1 + ""
      var day = today.getDate() + ""
      var hour = today.getHours() + ""
      var minute = today.getMinutes() + ""
      var second = today.getSeconds() + ""
      var orderNum = parseInt(year + month + day + hour + minute + second)
      this.SET_ORDER_NUM(orderNum)
    },
    computed: {
      ...mapState(['goodsInfo', 'address', 'loginToken', 'id', 'orderNum', 'goodsItem']),
      thisgoodsInfo() {
        const goodsList = []
        for (var i in this.goodsItems) {
          const list = this.getInfo(this.goodsItems[i].goodsID)
          console.log('list:', list[0])
          const list1 = list[0]
          const obj = {
            num: this.goodsItems[i].count
          }
          const obj1 = Object.assign({}, list1, obj)
          goodsList.push(obj1)
          console.log('goodsList:', goodsList)
        }
        return goodsList
      },
      // 总价
      totalPrice() {
        let sum = 0
        for (var i in this.thisgoodsInfo) {
          const p = this.thisgoodsInfo[i].selling_price * this.thisgoodsInfo[i].num
          sum = sum + p
        }
        return sum
      },
      getLabel() {
        return this.thisAdress[0].province_name + this.thisAdress[0].city_name + this.thisAdress[0].region_name + this
          .thisAdress[0].detail_address
      },
      // 获取收货地址信息
      getTitle() {
        return this.thisAdress[0].consignee + this.phoneNumFilter(this.thisAdress[0].consignee_phone)
      },
      // 收货地址
      thisAdress() {
        if (this.id === 0) {
          return this.address.filter(value => {
            return value.user_id === this.loginToken.userId && value.default_flag === 1
          })
        } else {
          return this.address.filter(value => {
            return value.user_id === this.loginToken.userId && value.address_id === parseInt(this.id)
          })
        }
      }
    }
  }
</script>

<style scoped>
  .order-confirm-page {
    background-color: #F2F2F2;
    height: 100%;
  }

  /deep/.set-header-ellipsis {
    visibility: hidden;
  }

  .item-block {
    margin: 18px 0;
  }

  .van-card {
    border-radius: 8px;
  }

  .total-info .van-cell__value {
    font-size: 12px;
    color: #262626;
    font-weight: 600;
  }
</style>
